<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX JSON 响应</title>
    <style>
        #result {
            width: 200px;
            height: 100px;
            border: solid 1px #90b
        }
    </style>
</head>

<body>
    <div id="result"></div>
</body>
<script lang="javascript">
    const BASE_URL = "http://localhost:8000"
    // get button element
    const result = document.getElementById("result");
    // bind key down action
    window.onkeydown = function () {
        // send request
        const xhr = new XMLHttpRequest();
        // set response data type
        xhr.responseType = 'json';
        xhr.open('get', BASE_URL + '/json-server', true);
        xhr.send();
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    // handle result
                    console.log(xhr.response)
                    // 1. transfer data by hand
                    // let data = JSON.parse(xhr.response);
                    // console.log(data);
                    // result.innerHTML = data.name + ": " + data.age
                    result.innerHTML = xhr.response.name + ": " + xhr.response.age
                } else {

                }
            }
        }
    }
</script>

</html>